import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';
import '../services/api_service.dart';
import '../services/app_state_service.dart';
import '../models/repair_order_model.dart';
import 'base_page.dart';

/// 工单管理页面
class RepairOrdersPage extends BasePage {
  const RepairOrdersPage({super.key});

  @override
  State<RepairOrdersPage> createState() => _RepairOrdersPageState();
}

class _RepairOrdersPageState extends BasePageState<RepairOrdersPage> {
  bool _hasLoaded = false; // 标记是否已经加载过数据
  int _lastLoadTime = 0; // 记录上次加载时间
  bool _isLoading = false;
  String _selectedFilter = '已提车'; // 当前选中的筛选标签
  String _searchQuery = ''; // 搜索关键词

  @override
  void initState() {
    super.initState();
    _loadRepairOrders();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    // 当页面依赖发生变化时（比如从其他页面切换回来），检查是否需要重新加载
    final currentTime = DateTime.now().millisecondsSinceEpoch;
    if (_hasLoaded && (currentTime - _lastLoadTime) > 5000) { // 如果距离上次加载超过5秒，则重新加载
      _loadRepairOrders();
    }
  }

  /// 加载工单列表
  Future<void> _loadRepairOrders() async {
    if (!mounted) return;
    
    setState(() {
      _isLoading = true;
    });

    try {
      final appState = Provider.of<AppStateService>(context, listen: false);
      final userTel = appState.currentUserTel ?? '';
      
      if (userTel.isNotEmpty) {
        print('开始调用工单列表接口，用户手机号: $userTel');
        final response = await ApiService.getAllRepairOrders(userTel);
        print('工单列表API响应: 成功=${response.isSuccess}, 消息=${response.message}');
        
        if (response.isSuccess && response.data != null) {
          final orders = response.data!;
          print('成功获取 ${orders.length} 个工单');
          print('工单数据类型: ${orders.runtimeType}');
          if (orders.isNotEmpty) {
            print('第一个工单类型: ${orders.first.runtimeType}');
          }
          
          // 保存所有工单到应用状态
          appState.setRepairOrders(orders);
          print('已保存所有工单到应用状态，数量: ${appState.repairOrders.length}');
          
          if (mounted) {
            setState(() {
              _isLoading = false;
            });
          }
        } else {
          print('工单列表API调用失败: ${response.message}');
          if (mounted) {
            setState(() {
              _isLoading = false;
            });
          }
        }
      } else {
        print('没有用户信息，无法加载工单');
        if (mounted) {
          setState(() {
            _isLoading = false;
          });
        }
      }
    } catch (e) {
      print('加载工单列表失败: $e');
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    } finally {
      _hasLoaded = true;
      _lastLoadTime = DateTime.now().millisecondsSinceEpoch;
    }
  }

  /// 根据状态加载工单列表
  Future<void> _loadRepairOrdersByStatus(String status) async {
    if (!mounted) return;
    
    setState(() {
      _isLoading = true;
    });

    try {
      final appState = Provider.of<AppStateService>(context, listen: false);
      final userTel = appState.currentUserTel ?? '';
      
      if (userTel.isNotEmpty) {
        print('开始调用工单列表接口，状态: $status，用户手机号: $userTel');
        
        // 调用工单列表查询接口，传入状态参数
        final response = await ApiService.getRepairOrdersByStatus(userTel, status);
        print('工单列表API响应: 成功=${response.isSuccess}, 消息=${response.message}');
        
        if (response.isSuccess && response.data != null) {
          final orders = response.data!;
          print('成功获取 ${orders.length} 个${status}工单');
          print('工单数据类型: ${orders.runtimeType}');
          if (orders.isNotEmpty) {
            print('第一个工单类型: ${orders.first.runtimeType}');
          }
          
          // 直接保存查询到的工单到应用状态
          appState.setRepairOrders(orders);
          print('已保存${status}工单到应用状态，数量: ${appState.repairOrders.length}');
          
          if (mounted) {
            setState(() {
              _isLoading = false;
            });
          }
        } else {
          print('工单列表API调用失败: ${response.message}');
          if (mounted) {
            setState(() {
              _isLoading = false;
            });
          }
        }
      } else {
        print('没有用户信息，无法加载工单');
        if (mounted) {
          setState(() {
            _isLoading = false;
          });
        }
      }
    } catch (e) {
      print('加载工单列表失败: $e');
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    } finally {
    _hasLoaded = true;
    _lastLoadTime = DateTime.now().millisecondsSinceEpoch;
    }
  }

  /// 根据状态筛选工单
  List<RepairOrder> _filterOrdersByStatus(List<RepairOrder> orders, String status) {
    return orders.where((order) {
      final repairType = order.repairType.toString().toLowerCase();
      switch (status) {
        case '维修中':
          // 维修中状态：包含"维修"、"进行"、"处理"等关键词
          return repairType.contains('维修') || 
                 repairType.contains('进行') || 
                 repairType.contains('处理') ||
                 repairType == 'inprogress' ||
                 repairType == 'repairing';
        case '已修完':
          // 已修完状态：包含"完成"、"修完"、"结束"等关键词
          return repairType.contains('完成') || 
                 repairType.contains('修完') || 
                 repairType.contains('结束') ||
                 repairType == 'completed' ||
                 repairType == 'finished';
        case '已提车':
          // 已提车状态：包含"提车"、"取车"、"交付"等关键词
          return repairType.contains('提车') || 
                 repairType.contains('取车') || 
                 repairType.contains('交付') ||
                 repairType == 'pickedup' ||
                 repairType == 'delivered';
        case '已取消':
          // 已取消状态：包含"取消"、"作废"、"终止"等关键词
          return repairType.contains('取消') || 
                 repairType.contains('作废') || 
                 repairType.contains('终止') ||
                 repairType == 'cancelled' ||
                 repairType == 'aborted';
        case '挂账中':
          // 挂账中状态：包含"挂账"、"欠款"、"未付"等关键词
          return repairType.contains('挂账') || 
                 repairType.contains('欠款') || 
                 repairType.contains('未付') ||
                 repairType == 'onaccount' ||
                 repairType == 'pending';
        default:
          return true;
      }
    }).toList();
  }

  @override
  PreferredSizeWidget? buildAppBar(BuildContext context) {
    return AppBar(
      title: const Text('工单管理'),
      backgroundColor: Colors.white,
      elevation: 0,
      actions: [
        IconButton(
          icon: const Icon(Icons.search),
          onPressed: () {
            // 搜索功能
            showInfo('搜索功能待实现');
          },
        ),
        IconButton(
          icon: const Icon(Icons.add),
          onPressed: () {
            // 添加工单功能
            showInfo('添加工单功能待实现');
          },
        ),
      ],
    );
  }

  @override
  Widget buildPageContent(BuildContext context) {
    return Consumer<AppStateService>(
      builder: (context, appState, child) {
        final orders = appState.repairOrders;
        
        // 调试信息
        print('=== 工单列表调试信息 ===');
        print('当前状态: $_selectedFilter');
        print('工单数量: ${orders.length}');
        print('是否正在加载: $_isLoading');
        if (orders.isNotEmpty) {
          print('第一个工单的repairType: ${orders.first.repairType}');
        }
        print('=== 调试信息结束 ===');
        
        return Column(
          children: [
            // 筛选标签
            _buildFilterTabs(),
            SizedBox(height: 8.h),
            
            // 搜索栏
            _buildSearchBar(),
            SizedBox(height: 8.h),
            
            // 工单列表
            Expanded(
              child: _isLoading
                  ? const Center(child: CircularProgressIndicator())
                  : orders.isEmpty
                      ? _buildEmptyState()
                      : RefreshIndicator(
                          onRefresh: () => _loadRepairOrdersByStatus(_selectedFilter),
                          child: ListView.builder(
                            padding: EdgeInsets.symmetric(vertical: 8.h),
                            itemCount: orders.length,
                            itemBuilder: (context, index) {
                              final order = orders[index];
                              return _buildRepairOrderCard(order, index + 1);
                            },
                          ),
                        ),
            ),
          ],
        );
      },
    );
  }

  /// 构建筛选标签
  Widget _buildFilterTabs() {
    final filters = ['维修中', '已修完', '已提车', '已取消', '挂账中'];
    
    return Container(
      height: 40.h,
      margin: EdgeInsets.symmetric(horizontal: 16.w),
      child: ListView.builder(
        scrollDirection: Axis.horizontal,
        itemCount: filters.length,
        itemBuilder: (context, index) {
          final filter = filters[index];
          final isSelected = _selectedFilter == filter;
          
          return GestureDetector(
            onTap: () {
              setState(() {
                _selectedFilter = filter;
              });
              // 根据筛选状态重新加载工单数据
              _loadRepairOrdersByStatus(filter);
            },
            child: Container(
              margin: EdgeInsets.only(right: 16.w),
              padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
              decoration: BoxDecoration(
                color: isSelected ? Theme.of(context).primaryColor : Colors.transparent,
                borderRadius: BorderRadius.circular(20.r),
              ),
              child: Text(
                filter,
                style: TextStyle(
                  fontSize: 14.sp,
                  color: isSelected ? Colors.white : Colors.grey[600],
                  fontWeight: isSelected ? FontWeight.w600 : FontWeight.normal,
                ),
              ),
            ),
          );
        },
      ),
    );
  }

  /// 构建搜索栏
  Widget _buildSearchBar() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w),
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
      decoration: BoxDecoration(
        color: Colors.grey[100],
        borderRadius: BorderRadius.circular(8.r),
      ),
      child: Row(
        children: [
          Icon(Icons.search, color: Colors.grey[600], size: 20.sp),
          SizedBox(width: 8.w),
          Expanded(
            child: TextField(
              decoration: const InputDecoration(
                hintText: '点击选择客户',
                border: InputBorder.none,
                contentPadding: EdgeInsets.zero,
              ),
              onChanged: (value) {
                setState(() {
                  _searchQuery = value;
                });
              },
            ),
          ),
        ],
      ),
    );
  }

  /// 构建空状态
  Widget _buildEmptyState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.assignment_outlined,
            size: 64.sp,
            color: Colors.grey[400],
          ),
          SizedBox(height: 16.h),
          Text(
            '暂无工单数据',
            style: TextStyle(
              fontSize: 16.sp,
              color: Colors.grey[600],
            ),
          ),
          SizedBox(height: 8.h),
          Text(
            '请先添加客户和工单',
            style: TextStyle(
              fontSize: 14.sp,
              color: Colors.grey[500],
            ),
          ),
        ],
      ),
    );
  }

  /// 获取筛选后的工单列表
  List<dynamic> _getFilteredOrders(List<dynamic> orders) {
    return orders.where((order) {
      // 根据筛选标签过滤 - 使用与 _filterOrdersByStatus 相同的逻辑
      bool matchesFilter = true;
      final repairType = order.repairType.toString().toLowerCase();
      
      switch (_selectedFilter) {
        case '维修中':
          matchesFilter = repairType.contains('维修') || 
                         repairType.contains('进行') || 
                         repairType.contains('处理') ||
                         repairType == 'inprogress' ||
                         repairType == 'repairing';
          break;
        case '已修完':
          matchesFilter = repairType.contains('完成') || 
                         repairType.contains('修完') || 
                         repairType.contains('结束') ||
                         repairType == 'completed' ||
                         repairType == 'finished';
          break;
        case '已提车':
          matchesFilter = repairType.contains('提车') || 
                         repairType.contains('取车') || 
                         repairType.contains('交付') ||
                         repairType == 'pickedup' ||
                         repairType == 'delivered';
          break;
        case '已取消':
          matchesFilter = repairType.contains('取消') || 
                         repairType.contains('作废') || 
                         repairType.contains('终止') ||
                         repairType == 'cancelled' ||
                         repairType == 'aborted';
          break;
        case '挂账中':
          matchesFilter = repairType.contains('挂账') || 
                         repairType.contains('欠款') || 
                         repairType.contains('未付') ||
                         repairType == 'onaccount' ||
                         repairType == 'pending';
          break;
      }
      
      // 根据搜索关键词过滤
      bool matchesSearch = _searchQuery.isEmpty ||
          (order.carCode?.toString() ?? '').toLowerCase().contains(_searchQuery.toLowerCase()) ||
          (order.customerName?.toString() ?? '').toLowerCase().contains(_searchQuery.toLowerCase());
      
      return matchesFilter && matchesSearch;
    }).toList();
  }

  Widget _buildRepairOrderCard(order, int index) {
    // 根据实际API数据设计工单卡片布局
    return Container(
      margin: EdgeInsets.only(bottom: 1.h),
      padding: EdgeInsets.all(0),
      decoration: BoxDecoration(
        color: Colors.white,
      ),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 左侧头像和客户信息区域（70dp宽度）
          Container(
            width: 70.w,
            child: Column(
              children: [
                // 头像
                Container(
                  margin: EdgeInsets.all(10.w),
                  width: 50.w,
                  height: 50.w,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(25.w),
                    border: Border.all(color: Colors.grey[300]!, width: 1),
                  ),
                  child: Container(
                    color: Colors.grey[200],
                    child: Icon(
                      Icons.person,
                      color: Colors.grey[400],
                      size: 24.w,
                    ),
                  ),
                ),
                // 客户姓名（使用车牌号作为显示）
                Text(
                  order.carCode,
                  style: TextStyle(
                    fontSize: 12.sp,
                    color: Colors.grey[600],
                  ),
                  textAlign: TextAlign.center,
                ),
                SizedBox(height: 2.h),
                // 客户状态
                Text(
                  order.iswatiinginshop == '1' ? '在店等' : '不在店等',
                  style: TextStyle(
                    fontSize: 11.sp,
                    color: Colors.grey[600],
                  ),
                  textAlign: TextAlign.center,
                ),
              ],
            ),
          ),
          
          // 中间内容区域
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 第一行：车牌号和支付信息
                Row(
                  children: [
                    // 车牌号
                    Expanded(
                      child: Text(
                        order.carCode,
                        style: TextStyle(
                          fontSize: 16.sp,
                          fontWeight: FontWeight.bold,
                          color: Colors.black87,
                        ),
                      ),
                    ),
                    // 右侧支付信息
                    Container(
                      width: 100.w,
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.end,
                        children: [
                          // 支付方式
                          Text(
                            _getPaymentMethodText(order.payType),
                            style: TextStyle(
                              fontSize: 10.sp,
                              color: Colors.black87,
                            ),
                          ),
                          SizedBox(height: 4.h),
                          // 状态标签
                          Container(
                            padding: EdgeInsets.symmetric(horizontal: 6.w, vertical: 2.h),
                            decoration: BoxDecoration(
                              color: Colors.grey[400],
                              borderRadius: BorderRadius.circular(4.r),
                            ),
                            child: Text(
                              '未知',
                              style: TextStyle(
                                fontSize: 10.sp,
                                color: Colors.white,
                              ),
                            ),
                          ),
                          SizedBox(height: 4.h),
                          // 总价标签
                          Text(
                            '总',
                            style: TextStyle(
                              fontSize: 11.sp,
                              color: Colors.black87,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
                
                // 第二行：维修项目
                Row(
                  children: [
                    // 维修项目
                    Expanded(
                      child: Text(
                        '维修项目: ${order.repairType?.isNotEmpty == true ? order.repairType : '暂无'}',
                        style: TextStyle(
                          fontSize: 12.sp,
                          color: Colors.grey[600],
                        ),
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                    // 右侧价格
                    Container(
                      width: 100.w,
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.end,
                        children: [
                          // 实付金额
                          Text(
                            '¥${order.saleMoney?.isNotEmpty == true ? order.saleMoney : '0'}',
                            style: TextStyle(
                              fontSize: 10.sp,
                              color: Colors.red[600],
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
                
                // 分割线
                Container(
                  height: 0.5.h,
                  color: Colors.grey[300],
                  margin: EdgeInsets.symmetric(vertical: 4.h),
                ),
                
                // 第三行：时间信息和序号
                Row(
                  children: [
                    // 时间信息
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          // 进店时间
                          Text(
                            '进门店时间: ${order.entershoptime?.isNotEmpty == true ? order.entershoptime : '暂无'}',
                            style: TextStyle(
                              fontSize: 12.sp,
                              color: Colors.grey[600],
                            ),
                          ),
                          SizedBox(height: 2.h),
                          // 预提车时间
                          Text(
                            '预提车时间: ${order.wantedcompletedtime?.isNotEmpty == true ? order.wantedcompletedtime : '暂无'}',
                            style: TextStyle(
                              fontSize: 12.sp,
                              color: Colors.grey[600],
                            ),
                          ),
                        ],
                      ),
                    ),
                    // 序号
                    Container(
                      width: 30.w,
                      height: 30.w,
                      decoration: BoxDecoration(
                        color: Colors.blue[600],
                        borderRadius: BorderRadius.circular(15.w),
                      ),
                      child: Center(
                        child: Text(
                          '$index',
                          style: TextStyle(
                            fontSize: 16.sp,
                            color: Colors.white,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 获取支付方式文本
  String _getPaymentMethodText(String? payType) {
    if (payType == null) return '现金';
    switch (payType) {
      case '0': return '现金';
      case '1': return '会员卡支付';
      case '2': return '微信';
      case '3': return '支付宝';
      default: return '现金';
    }
  }

  /// 获取状态颜色
  Color _getStatusColor(String status) {
    switch (status.toLowerCase()) {
      case 'inprogress':
      case 'repairing':
      case '维修中':
        return Colors.orange;
      case 'completed':
      case 'finished':
      case '已修完':
        return Colors.green;
      case 'pickedup':
      case 'delivered':
      case '已提车':
        return Colors.blue;
      case 'cancelled':
      case 'aborted':
      case '已取消':
        return Colors.red;
      case 'onaccount':
      case 'pending':
      case '挂账中':
        return Colors.purple;
      default:
        return Colors.grey;
    }
  }

  /// 获取状态文本
  String _getStatusText(String status) {
    switch (status.toLowerCase()) {
      case 'inprogress':
      case 'repairing':
        return '维修中';
      case 'completed':
      case 'finished':
        return '已修完';
      case 'pickedup':
      case 'delivered':
        return '已提车';
      case 'cancelled':
      case 'aborted':
        return '已取消';
      case 'onaccount':
      case 'pending':
        return '挂账中';
      default:
        return '未知';
    }
  }

  /// 格式化日期
  String _formatDate(String dateStr) {
    if (dateStr.isEmpty) return '';
    try {
      final date = DateTime.parse(dateStr);
      return '${date.month}/${date.day}';
    } catch (e) {
      return dateStr;
    }
  }

}
